<template>
  <div>
    <el-image
      fit="contain"
      :preview-src-list="showImgList"
      id="imageWrapper"
      :src="qrCode"
      alt="二维码"
    />
  </div>
</template>

<script>
import QRCode from 'qrcode'
export default {
  name: 'urlQrCode',
  props: {
    link: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      qrCode: ''
    }
  },
  computed: {
    showImgList() {
      let imgAry = []
      imgAry[0] = this.qrCode
      return imgAry
    }
  },
  mounted() {
    this.getQRcode(this.link).then((img) => {
      this.qrCode = img
    })
  },
  methods: {
    async getQRcode(url) {
      const cofing = {
        errorCorrectionLevel: 'L',
        type: 'image/jpeg',
        quality: 1,
        margin: 1,
        color: {
          dark: '#000',
          light: '#fff'
        },
        width: 300, // 二维码宽度，单位像素
        height: 300 // 二维码高度，单位像素
      }
      try {
        const qrcode = await QRCode.toDataURL(url, cofing)
        return qrcode
      } catch (err) {
        console.error(err)
      }
    }
  },
  watch: {
    link: {
      handler(newVal, oldVal) {
        if (newVal !== oldVal) {
          this.getQRcode(this.link).then((img) => {
            this.qrCode = img
          })
        }
      },
      deep: true
    }
  }
}
</script>

<style>
#imageWrapper {
  width: 100px;
  height: 100px;
}
</style>
